//
//  NativeCollectionViewCell.swift
//  iPhone
//
//  Created by Toj on 5/24/23.
//

import UIKit
import GoogleMobileAds

class NativeCollectionViewCell: UICollectionViewCell {
    
    private weak var _delegate: UICollectionViewCellDelegate?
    private let placeholder = "com_placeholder_336x189".to_image
    
    var cellModel: NativeAdCellModel? { didSet {
        guard let model = cellModel else { return }
        
        indexLabel.text = model.spaceID
        
        imageView.image = placeholder
        imageView.isHidden = false
        
        moduleView.isHidden = model.isAd
        
        guard !model.isAd else {
            loadNativeAd(model)
            return
        }
        nativeAdView.isHidden = true
        nameLabel.text = model.name
        descripLabel.text = model.descrip
        guard let url = URL(string: model.materials) else {
            return
        }
        imageView.kf.setImage(with: url)
    } }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupMakeAddSubviews()
        setupMakeInitialize()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setupMakeLayoutSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
       dispose()
    }
    
    func dispose() {
        _adLoader?.delegate = nil
        _adLoader = nil
    }
    
    /* index */
    private lazy var indexLabel: UILabel = {
        let view = UILabel()
        view.textColor = .black
        return view
    }()
    
    /* imageView */
    private lazy var imageView = UIImageView()
    
    private lazy var moduleView = UIView()
    
    /* nameLabel */
    private lazy var nameLabel: UILabel = {
        let view = UILabel()
        view.textColor = .black
        return view
    }()

    /* descripLabel */
    private lazy var descripLabel: UILabel = {
        let view = UILabel()
        view.textColor = .black
        return view
    }()
 
    private lazy var nativeAdView: STNativeAdmobView = {
        let view = STNativeAdmobView()
        return view
    }()
    
    deinit {
        print("-->toj: class: \(cm_objectName), func: \(#function)")
    }
    private var _adLoader: GADAdLoader?
}

extension NativeCollectionViewCell {
    func loadNativeAd(_ model: NativeAdCellModel) {
        let spaceID = cellModel?.spaceID ?? ""
        print("-->toj: class:\(cm_className), func: \(#function), spaceID: spaceID:\(spaceID),")
        
        if _adLoader?.isLoading == true {
            dispose()
        }
        
        imageView.isHidden = nativeAdView.nativeAd != nil
        nativeAdView.isHidden = !imageView.isHidden
        
        let materials = model.materials
        let vc = UIViewController.vc_currentNavigationTopViewController
        
        let options = GADNativeAdViewAdOptions()
        options.preferredAdChoicesPosition = .topLeftCorner
        let adLoader = GADAdLoader(adUnitID: materials, rootViewController: vc,
                                   adTypes: [.native], options: [options])
        adLoader.delegate = self
        let request = GADRequest()
        adLoader.load(request)
        _adLoader = adLoader
    }
}

extension NativeCollectionViewCell: GADNativeAdLoaderDelegate {
    
    func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
        nativeAdView.isUserInteractionEnabled = false
        nativeAdView.isHidden = false
        
        let spaceID = cellModel?.spaceID ?? ""
        print("-->toj:spaceID: \(spaceID), adLoader: didReceive")
        nativeAd.delegate = self
        // 设置数据源
        nativeAdView.nativeAd = nativeAd
        
        
        print("-->toj: aspectRatio:\(nativeAd.mediaContent.aspectRatio)")
        
        let mediaContent = nativeAd.mediaContent
        guard mediaContent.hasVideoContent else {
            return
        }
        mediaContent.videoController.delegate = self
    }
    
    func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error)  {
        let spaceID = cellModel?.spaceID ?? ""
        print("-->toj: spaceID:\(spaceID), didFailToReceiveAdWithError:\(error.localizedDescription)")
        nativeAdView.isHidden = true
        imageView.isHidden = false
        nativeAdView.isUserInteractionEnabled = false
    }
}

extension NativeCollectionViewCell: GADVideoControllerDelegate {
    
    func videoControllerDidEndVideoPlayback(_ videoController: GADVideoController) {
        
    }
}

// MARK: - GADNativeAdDelegate implementation
extension NativeCollectionViewCell: GADNativeAdDelegate {
    
    func nativeAdDidRecordImpression(_ nativeAd: GADNativeAd) {
        let spaceID = cellModel?.spaceID ?? ""
        print("\(#function) called, spaceID:\(spaceID)")
        imageView.isHidden = true
        nativeAdView.isUserInteractionEnabled = true
    }
    
//    func nativeAdDidRecordClick(_ nativeAd: GADNativeAd) {
//        print("\(#function) called")
//    }
//
//    func nativeAdWillPresentScreen(_ nativeAd: GADNativeAd) {
//        print("\(#function) called")
//    }
//
//    func nativeAdWillDismissScreen(_ nativeAd: GADNativeAd) {
//        print("\(#function) called")
//    }
//
//    func nativeAdDidDismissScreen(_ nativeAd: GADNativeAd) {
//        print("\(#function) called")
//    }
//
//    func nativeAdWillLeaveApplication(_ nativeAd: GADNativeAd) {
//        print("\(#function) called")
//    }
}

extension NativeCollectionViewCell: UICollectionViewCellDataSource {
    
    var delegate: UICollectionViewCellDelegate? {
        get {
            return _delegate
        }
        set {
            _delegate = newValue
        }
    }
    
    var dataModel: UICollectionViewCellModelProtocol? {
        get {
            return cellModel
        }
        set {
            cellModel = newValue as? NativeAdCellModel
        }
    }
}

extension NativeCollectionViewCell {
    
    private func setupMakeAddSubviews() {
        contentView.addSubview(nativeAdView)
        contentView.addSubview(moduleView)
        contentView.addSubview(imageView)
        contentView.addSubview(indexLabel)
        
        moduleView.addSubview(descripLabel)
        moduleView.addSubview(nameLabel)
    }
    
    private func setupMakeLayoutSubviews() {
        nativeAdView.snp.makeConstraints { make in
            make.center.equalTo(contentView)
            make.height.width.equalTo(contentView)
        }
        
        moduleView.snp.makeConstraints { make in
            make.edges.equalTo(contentView)
        }
        
        imageView.snp.makeConstraints { make in
            make.left.right.top.equalTo(contentView)
            make.height.equalTo(189)
        }
        
        nameLabel.snp.makeConstraints { make in
            make.left.right.equalTo(contentView)
            make.top.equalTo(imageView.snp.bottom)
            make.height.equalTo(15)
        }
        
        descripLabel.snp.makeConstraints { make in
            make.left.right.equalTo(contentView)
            make.top.equalTo(nameLabel.snp.bottom)
            make.height.equalTo(15)
        }
        
        indexLabel.snp.makeConstraints { make in
            make.center.equalTo(contentView)
        }
    }
    
    private func setupMakeInitialize() {
        contentView.backgroundColor = .random
    }
}
